package com.sptpc.demo1.service.impl;

import com.sptpc.demo1.model.Category;
import com.sptpc.demo1.model.Drink;
import com.sptpc.demo1.repository.CategoryRepository;
import com.sptpc.demo1.repository.DrinkRepository;
import com.sptpc.demo1.service.ICategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.util.List;
@Service
public class CategoryJpaService implements ICategoryService {
    @Autowired
    public CategoryRepository categoryRepository;
    @Autowired
    public DrinkRepository drinkRepository;

    @Override
    public List<Category> getAllCategories() {
        return categoryRepository.findAll();
    }

    @Override
    public Category getCategoryById(Integer id) {
        return null;
    }

    @Override
    public List<Category> getAllCategory() {
        return null;
    }

    @Override
    public void addNewDrink(Category category) {

    }

    @Override
    public void deleteDrinkById(Integer id) {

    }

    @Override
    public void updateDrink(Category category) {

    }

    @Override
    public Category getAllCategoryById(int toIntExact) {
        return null;
    }

    @Override
    @Transactional(rollbackOn = Exception.class)
    public void deleteCategoryById(Integer id) {


        //1.将drink中关联该Category的drink的category属性更新为null
        //1.1查询出和category关联的drink
        List<Drink> drinks = drinkRepository.findDrinkByCategory_Id(id);
        for (Drink drink : drinks) {
            drink.setCategory(null);
            drinkRepository.save(drink);
        }
        //2.删除指定分类
        categoryRepository.deleteById(id);

    }
}